package com.zl.task.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zl.task.dao.ServiceOrderMapper;
import com.zl.task.dao.ServiceProductMapper;
import com.zl.task.dto.ProductDTO;
import com.zl.task.pojo.ServiceChina;
import com.zl.task.pojo.ServiceMechanism;
import com.zl.task.pojo.ServiceOrder;
import com.zl.task.pojo.ServiceProduct;
import com.zl.task.service.IServiceChinaService;
import com.zl.task.service.IServiceEnterprisedService;
import com.zl.task.service.IServiceMechanismService;
import com.zl.task.service.IServiceProductService;
import com.zl.task.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.zl.task.commom.ServiceCode.ENTERPRISE_TYPE;
import static com.zl.task.commom.ServiceCode.MECHANISM_TYPE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yinlingeng
 * @since 2021-07-23
 */
@Service
public class ServiceProductServiceImpl extends ServiceImpl<ServiceProductMapper, ServiceProduct> implements IServiceProductService {

    @Autowired
    private IServiceChinaService chinaService;
    @Autowired
    private IServiceMechanismService mechanismService;
    @Resource
    ServiceOrderMapper orderMapper;


    /**
     * 发布产品
     *
     * @param productDTO
     * @return
     */
    @Override
    public String saveProduct(ProductDTO productDTO) throws Exception {
        ServiceProduct serviceProduct = new ServiceProduct();
        serviceProduct.setProductName(productDTO.getProductName());
        serviceProduct.setProductMechanism(productDTO.getProductMechanism());
        serviceProduct.setProductProvince(productDTO.getProductProvince());
        serviceProduct.setProductCity(productDTO.getProductCity());
        serviceProduct.setProductHandle(productDTO.getProductHandle());
        serviceProduct.setProductProblem(productDTO.getProductProblem());
        serviceProduct.setProductSuccess(productDTO.getProductSuccess());
        serviceProduct.setProductType(productDTO.getProductType());
        serviceProduct.setProductStatus(productDTO.getProductStatus());
        if (baseMapper.insert(serviceProduct)>0) {
            return "发布成功";
        }
        throw new Exception("发布失败");
    }

    /**
     * 修改产品信息
     * 隐藏/展示
     * @param productDTO -
     * @return Boolean
     */
    @Override
    public Boolean updateProduct(ProductDTO productDTO) throws Exception {
        // 查找该产品的订单
        List<ServiceOrder> serviceOrders = orderMapper.selectList(Wrappers.<ServiceOrder>lambdaQuery()
                .eq(ServiceOrder::getOrderProduct, productDTO.getProductId()));
        if (null == serviceOrders ||serviceOrders.isEmpty()) {
            System.out.println("jin");
            ServiceProduct serviceProduct = new ServiceProduct();
            serviceProduct.setProductId(productDTO.getProductId());
            serviceProduct.setProductName(productDTO.getProductName());
            serviceProduct.setProductMechanism(productDTO.getProductMechanism());
            serviceProduct.setProductProvince(productDTO.getProductProvince());
            serviceProduct.setProductCity(productDTO.getProductCity());
            serviceProduct.setProductHandle(productDTO.getProductHandle());
            serviceProduct.setProductProblem(productDTO.getProductProblem());
            serviceProduct.setProductSuccess(productDTO.getProductSuccess());
            serviceProduct.setProductType(productDTO.getProductType());
            serviceProduct.setProductStatus(productDTO.getProductStatus());
            if (baseMapper.updateById(serviceProduct)>0) {
                return true;
            }else {
                throw new Exception("该产品不存在");
            }
        }else {
            throw new Exception("该产品已有购买订单不可大幅度修改产品信息，可将产品下架重新上架产品");
        }
    }

    /**
     * 上下架产品 （隐藏）
     *
     * @return Boolean
     * @throws Exception -
     */
    @Override
    public Boolean hideProduct(Long productId,Long userId,Integer productStatus) throws Exception {
        ServiceProduct serviceProduct = new ServiceProduct();
        // 商品为下架状态，将商品上架
        if (productStatus == 0) {
            serviceProduct.setProductId(productId);
            serviceProduct.setProductMechanism(userId.toString());
            serviceProduct.setProductStatus(1);
            if (baseMapper.updateById(serviceProduct)>0) {
                return true;
            }
            // 商品为上架状态，在没有订单服务的状态下将商品下架
        }else if (productStatus == 1 ){
            List<ServiceOrder> serviceOrders = orderMapper.selectList(Wrappers.<ServiceOrder>lambdaQuery()
                    .eq(ServiceOrder::getOrderProduct, productId)
                    .ne(ServiceOrder::getOrderStatus,1)
                    .ne(ServiceOrder::getOrderStatus,99));
            if (serviceOrders.isEmpty()) {
                serviceProduct.setProductId(productId);
                serviceProduct.setProductMechanism(userId.toString());
                serviceProduct.setProductStatus(0);
                if (baseMapper.updateById(serviceProduct)>0) {
                    return true;
                }
            }else {
                throw new Exception("有订单未完成服务，请服务完成后再进行下架");
            }
        }
        throw new Exception("操作失败");
    }


    /**
     * 产品展示
     * 产品状态为1 为显示 0为隐藏
     * @param typeId - 产品类型id
     * @param page - 页码
     * @param size - 页数
     * @param userType - 用户类型
     * @param userId - 用户Id
     * @return List<ServiceProduct>
     */
    @Override
    public Object listProduct(Integer typeId,Integer page,Integer size,String userType,Long userId) throws Exception {
        if (ENTERPRISE_TYPE.equals(userType)) {
            if (page > 0 && size > 0 && typeId > 0) {
                PageHelper.startPage(page, size);
                return new PageInfo<>(showProductCommon(baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductStatus, 1)
                        .eq(ServiceProduct::getProductType, typeId))));
            } else if (page > 0 && size > 0) {
                PageHelper.startPage(page, size);
                return new PageInfo<>(showProductCommon(baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductStatus, 1))));
            }
            if (typeId > 0) {
                return showProductCommon(baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductStatus, 1)
                        .eq(ServiceProduct::getProductType, typeId)));
            } else {
                return showProductCommon(baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductStatus, 1)));
            }
        } else if (MECHANISM_TYPE.equals(userType)) {
            if (page > 0 && size > 0 && typeId > 0) {
                PageHelper.startPage(page, size);
                return new PageInfo<>(showProductCommon(baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductType, typeId)
                        .eq(ServiceProduct::getProductMechanism, userId))));
            } else if (page > 0 && size > 0) {
                PageHelper.startPage(page, size);
                return new PageInfo<>(showProductCommon(baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductMechanism,userId))));
            }
            if (typeId > 0) {
                return showProductCommon( baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductType, typeId)
                        .eq(ServiceProduct::getProductMechanism,userId)));

            } else {
                return showProductCommon( baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery()
                        .eq(ServiceProduct::getProductMechanism,userId)));
            }
        }
        throw new Exception("系统错误");
    }



    /**
     * 产品展示公共方法
     * @param serviceProducts
     * @return
     */
    public List<ProductVo> showProductCommon(List<ServiceProduct> serviceProducts)throws Exception{
        List<ProductVo> productVos = new ArrayList<>();
        List<ServiceChina> serviceChinasProvince = chinaService.listProvince();
        List<ServiceChina> serviceChinasCity = chinaService.listCity();
        List<ServiceMechanism> serviceMechanisms = mechanismService.listMechanism();
        if (null == serviceProducts || serviceProducts.isEmpty()){
            throw new Exception("暂无产品");
        }
        for (ServiceProduct serviceProduct : serviceProducts) {
            ProductVo productVo = new ProductVo();
            productVo.setProductId(serviceProduct.getProductId());
            productVo.setProductName(serviceProduct.getProductName());
            ServiceMechanism mechanism = serviceMechanisms.stream().filter(serviceMechanism -> serviceMechanism.getMechanismId().toString().equals(serviceProduct.getProductMechanism())).findAny().orElse(null);
            productVo.setProductMechanism(mechanism.getMechanismName());
            ServiceChina chinaProvince = serviceChinasProvince.stream().filter(serviceChina -> serviceChina.getNumber().equals(serviceProduct.getProductProvince())).findAny().orElse(null);
            productVo.setProductProvince(chinaProvince.getName());
            ServiceChina chinaCity = serviceChinasCity.stream().filter(chinaCitys -> chinaCitys.getNumber().equals(serviceProduct.getProductCity())).findAny().orElse(null);
            productVo.setProductCity(chinaCity.getName());
            productVo.setProductHandle(serviceProduct.getProductHandle());
            productVo.setProductProblem(serviceProduct.getProductProblem());
            productVo.setProductSuccess(serviceProduct.getProductSuccess());
            productVo.setProductType(serviceProduct.getProductType());
            productVo.setProductStatus(serviceProduct.getProductStatus());
            productVos.add(productVo);
        }
        return productVos;
    }


    /**
     * 所有产品
     *
     * @return
     */
    @Override
    public List<ServiceProduct> listAllProduct() {
        return baseMapper.selectList(Wrappers.<ServiceProduct>lambdaQuery());
    }

    /**
     * 产品删除
     * @param userId - 机构用户id
     * @param productId - 产品id
     * @return
     * @throws Exception
     */
    @Override
    public Boolean deleteProduct(Long userId,String productId)throws Exception {
        if (orderMapper.selectCount(Wrappers.<ServiceOrder>lambdaQuery()
                .eq(ServiceOrder::getOrderMechanism, userId)
                .eq(ServiceOrder::getOrderProduct, productId)
                .ne(ServiceOrder::getOrderStatus, 99)) == 0) {
            if (baseMapper.deleteById(productId)>0) {
                List<ServiceOrder> serviceOrders = orderMapper.selectList(Wrappers.<ServiceOrder>lambdaQuery()
                        .eq(ServiceOrder::getOrderProduct, productId));
                if (serviceOrders.isEmpty()) {
                   return true;
                }else {
                    for (ServiceOrder serviceOrder : serviceOrders) {
                        if (orderMapper.deleteById(serviceOrder.getOrderCode())>0) {
                            return true;
                        }
                    }
                }
            }else {
                throw new Exception("该产品不存在");
            }
        }
       throw new Exception("该产品有服务订单不可删除");

    }
}
